package model.fshare.client;

import java.io.File;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;


import model.fshare.Interface.FileTransmistObserver;
import model.fshare.Interface.FileUpload;
import model.infocenter.ServerInformations;

public class FileUploader implements FileUpload
{
	
	@Override
	public int upload(int roomId, int userId, File file, FileTransmistObserver observer) 
	{
		if ( !file.exists() || file.isDirectory() )
		{
			return 1;
		}
		
		
		try 
		{
			String serverIp = ServerInformations.getInstance().getIP();
			Socket socketForRequest = new Socket( serverIp, 5998 );
			
			PrintWriter requestSender = new PrintWriter( socketForRequest.getOutputStream() );			requestSender.println( "" + roomId );
			requestSender.flush();
			requestSender.println( "" + userId );
			requestSender.flush();
			String fileName = file.getName();
			requestSender.println( fileName );
			requestSender.flush();
			
			// Before upload,
			// client must get permission from server.
			ObjectInputStream responseReader = new ObjectInputStream( socketForRequest.getInputStream() );
			boolean allowed = (Boolean) responseReader.readObject();
			if ( allowed )
			{
				FileUploading fUploading = new FileUploading( file, socketForRequest, observer );
				Thread uThread = new Thread( fUploading );
				uThread.start();
				return 0;
			}

			return 2;
		}
		catch ( Exception e ) 
		{
			e.printStackTrace();
		}
		
		return 3;
	}

}
